package niuke;

import java.util.*;

/**
 * 按之字形顺序打印二叉树
 */
public class Solution4 {
    public ArrayList<ArrayList<Integer> >Print(TreeNode pRoot) {
        Queue<TreeNode> queue = new LinkedList<>();
        ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
        
        if(pRoot == null  ) return ret;
        queue.offer(pRoot);
        int flag = 1;

        while (!queue.isEmpty()) {
            ArrayList<Integer> list = new ArrayList<>();
            //计算队列中的元素个数
            int size = queue.size();
            while (size-- > 0) {
                TreeNode tmp = queue.poll();
                list.add(tmp.val);

                if( tmp.left!=null) {
                    queue.offer(tmp.left);
                }
                if( tmp.right!=null){
                    queue.offer(tmp.right);
                }
            }
            //此时要反转数组
            if(flag == -1){
                Collections.reverse( list);
            }
            flag = -flag;
            ret.add(list);
        }
        return ret;
    }

}